use anyhow::Context;
use slack_api::chat::PostMessageRequest;

const SLACK_TOKEN: &'static str = "xoxb-5035662710-1303363102804-D7jSKcu8Mor6mW9DQQehhL13";


use governor::state::{direct::NotKeyed, InMemoryState};
use governor::clock::DefaultClock;

static SLACK_RATE_LIMITER: once_cell::sync::Lazy<governor::RateLimiter<NotKeyed, InMemoryState, DefaultClock>> = once_cell::sync::Lazy::new(|| {
    governor::RateLimiter::direct(
        governor::Quota::with_period(std::time::Duration::from_secs(5*60))
            .context("fail to create rate limiter").unwrap()
            .allow_burst(std::num::NonZeroU32::new(5).unwrap())
    )
});

// PostMessageRequest{channel, text, , ..Default::default()}\
pub async fn send<'a>(req: PostMessageRequest<'a>) -> anyhow::Result<()> {
    anyhow::ensure!(
        req.channel == "#coin_feed_noti" || req.channel == "@donggu",
        "@feed_relay sends the msg to a wrong channel"
    );
    if SLACK_RATE_LIMITER.check().is_ok() {
        slack_api::chat::post_message(&slack_api::requests::default_client()?, SLACK_TOKEN, &req)
        .await
        .with_context(|| format!("fail to send slack msg. tried to send {:?}", req))?;
    }
    
    Ok(())
}

